package com.magical.controller;

import com.magical.entity.Files;
import com.magical.service.FilesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


@Controller
@RequestMapping("/files")
public class FilesController {

    @Autowired
    private FilesService filesService;

    public List<File> loadFiles(String fileDir,String ParentId) throws IOException {
        List<File> list=new ArrayList<File>();
        File file = new File(fileDir);
        File[] files = file.listFiles();
        if(files==null)
            return null;
        for (File f : files) {
            if (f.isFile()) {
                Files temp=new Files();
                String currentTime=Long.toString(System.currentTimeMillis());
                String originalFilename = f.getName();
                String filepath=f.getAbsolutePath();
                int size= (int) (f.length()/1024);
                String type=null;
                try {
                    type = java.nio.file.Files.probeContentType(f.toPath()).split("/")[0];
                }catch (Exception e){
                    type="other";
                }
                temp.setFileId(currentTime);
                temp.setFileName(originalFilename);
                temp.setFileSize(size);
                temp.setUserId(1);
                temp.setFatherId(ParentId);
                temp.setFullPath(filepath);
                switch (type){
                    case "text":temp.setFiletypeId(2);break;
                    case "image":temp.setFiletypeId(4);break;
                    default:temp.setFiletypeId(6);

                }
                filesService.upload(temp);
                list.add(f);
            } else if (f.isDirectory()) {
                Files temp=new Files();
                String currentTime=Long.toString(System.currentTimeMillis());
                String originalFilename = f.getName();
                String filepath=f.getAbsolutePath();
                int size= (int) (f.length()/1024);
                String type="Directory";
                temp.setFileId(currentTime);
                temp.setFileName(originalFilename);
                temp.setFileSize(size);
                temp.setUserId(1);
                temp.setFatherId(ParentId);
                temp.setFullPath(filepath);
                temp.setFiletypeId(5);
                filesService.upload(temp);
                loadFiles(f.getAbsolutePath(),currentTime);
            }
        }
        for (File f1 : list) {
            System.out.println(f1.getName());
        }
        return list;
    }

    @RequestMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files =multipartRequest.getFiles("files");
        String[] paths=request.getParameterValues("paths");
        if(!files.isEmpty()) {
            String path = System.getProperty("root.webapp")+"upload/";
            for(int i=0;i<paths.length;i++) {
                File temp=new File(path+paths[i]);
                if(!temp.getParentFile().exists())
                    temp.getParentFile().mkdirs();
                if(!temp.exists())
                    files.get(i).transferTo(temp);
            }
            try{
                File root=new File(path);
                File file=new File(path+paths[1]).getParentFile();
                String rootName=paths[1].split("/")[0];
                File[] rootDir=root.listFiles();
                for(File f:rootDir)
                    if(f.getName().equals(rootName))
                        file = f;
                List<File> list=loadFiles(file.getAbsolutePath(),null);
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("失败了");
            }
        }
        return "success";
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    public String uploadFile(HttpServletRequest request) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        if (!file.isEmpty()) {
            String path = System.getProperty("root.webapp") + "upload\\";
            String currentTime=Long.toString(System.currentTimeMillis());
            String originalFilename = file.getOriginalFilename();
            String filePath = path + originalFilename;
            System.out.println("filePath: " + filePath);
            int size= (int) (file.getSize()/1024);
            String type=file.getContentType().split("/")[0].toString();
            File dest = new File(filePath);
            if (!(dest.exists())) {
                file.transferTo(dest);
                Files uploadFile = new Files();
                uploadFile.setFileId(currentTime);
                uploadFile.setFileName(originalFilename);
                uploadFile.setFileSize(size);
                uploadFile.setUserId(1);
                uploadFile.setFullPath(filePath);
                uploadFile.setFiletypeId(1);
                try{
                    filesService.upload(uploadFile);
                    return uploadFile.getFileId();
                }catch (Exception e){
                    e.printStackTrace();
                    return "failed";
                }
            }
        }
        return "success";
    }
}
